package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Yummy
 * @version 1.0
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")    // 每分钟执行一次
    public void processTimeoutOrders() {
        LocalDateTime now = LocalDateTime.now();
        log.info("处理超时订单, {}", now);
        // 处理超时订单的逻辑
        LocalDateTime orderTime = now.minusMinutes(15); // 假设超时订单为下单时间超过15分钟的订单
        List<Orders> timeoutOrders = orderMapper.getByStatusAndOrderTimeLT(Orders.UN_PAID, orderTime);
        if (timeoutOrders!= null && !timeoutOrders.isEmpty()) {
            for (Orders order : timeoutOrders) {
                // 将超时订单状态改为已取消
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时未支付，已自动取消");
                order.setCancelTime(now);
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")    // 每天凌晨1点执行
    public void processDeliveryOrders() {
        LocalDateTime now = LocalDateTime.now();
        log.info("处理一直处于派送中的订单, {}", now);
        // 处理派送中订单的逻辑
        LocalDateTime orderTime = now.minusMinutes(60);    // 假设派送中订单为下单时间超过1小时的订单(前一天的订单)
        List<Orders> deliveryOrders = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, orderTime);
        if (deliveryOrders != null && !deliveryOrders.isEmpty()) {
            for (Orders order : deliveryOrders) {
                // 将派送中订单状态改为已完成
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(now);
                orderMapper.update(order);
            }
        }
    }
}
